package com.cyandpos.pad.offline.offlinedb;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import java.lang.reflect.Field;

public class Sqldb {
    private static final String TAG = "Sqldb";
    private Context context;
    private SqlHelper sqliteHelper;
    private String database;

    public Sqldb(Context context) {
        this.context = context;
    }

    public boolean isOpen() {
        if (sqliteHelper != null && sqliteHelper.isOpen())
            return true;

        return false;
    }
    public boolean open(String database) {
        if (sqliteHelper == null)
            sqliteHelper = new SqlHelper(context, database, null, 1);

        if (sqliteHelper != null) {
            this.database = database;
            return sqliteHelper.open(database);
        }

        return false;
    }

    // 重新打开库
    public boolean reOpen() {
        if (sqliteHelper == null)
            sqliteHelper = new SqlHelper(context, database, null, 1);

        if (sqliteHelper != null)
            return sqliteHelper.open(database);

        return false;
    }

    public void close() {
        if (sqliteHelper != null)
            sqliteHelper.close();
    }

    public void execSQL(String sql) {
        try {
            sqliteHelper.execSQL(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean execuSQL(String sql) {
        try {
            execSQL(sql);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    public boolean beginTransaction() {
        return sqliteHelper.beginTransaction();
    }

    public boolean setTransactionSuccessful() {
        return sqliteHelper.setTransactionSuccessful();
    }

    public boolean endTransaction() {
        return sqliteHelper.endTransaction();
    }

    /**
     * 带事物的增删改操作
     * @param sql
     */
    public void execSql(String sql) {
        try {
            sqliteHelper.beginTransaction();
            sqliteHelper.execSQL(sql);
            sqliteHelper.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
            Log.v(TAG, "执行数据库操作失败");
        } finally {
            sqliteHelper.endTransaction();
        }
    }

    /**
     * 执行SQL进行增、删、改操作
     * @param sql
     * @param values  参数
     */
    public void execSQL(String sql, String[] values) {
        try {
            sqliteHelper.execSQL(sql, values);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行添加操作
     *
     * @param tableName 表名称
     * @param values    集合对象，以键值对的形式存储values.put("列名",值);
     */
    public boolean insert(String tableName, ContentValues values) {
        try {
            boolean isInsert=sqliteHelper.insert(tableName, values);
            return isInsert;
        } catch (Exception e) {
            e.printStackTrace();
        }
         return false;
    }

    /**
     * 修改
     *
     * @param tableName   表名称
     * @param values      ContentValeus对象，以键值对的形式存储，如：values.put("列名",值);
     * @param whereClause where子句，如：id=?
     * @param wherevalues where子句的占位符赋值，如：new String[]{值}
     */
    public boolean update(String tableName, ContentValues values, String whereClause, String[] wherevalues) {
        try {
            return sqliteHelper.update(tableName, values, whereClause, wherevalues);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除
     *
     * @param tableName   表名称
     * @param whereClause 删除条件
     * @param whereArgs   条件赋值
     */
    public boolean delete(String tableName, String whereClause, String[] whereArgs) {
        try {
            return sqliteHelper.delete(tableName, whereClause, whereArgs);
        } catch (Exception e) {
            e.printStackTrace();
        }
      return false;
    }

    /**
     * 查询
     *
     * @param sql  CRUD查询语句
     * @param args 参数
     * @return 返回值
     */
    public Cursor find(String sql, String[] args) {
        Cursor cur = null;
        try {
            cur = sqliteHelper.find(sql, args);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return cur;
    }

    public Cursor find(String sql) {
        Cursor cur = null;
        try {
            cur = find(sql, null);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return cur;
    }

    /**
     * 查询一列的值
     *
     * @param sql
     * @return
     */
    public Object selectOneData(String sql) {
        Object obj = null;
        Cursor cursor = null;

        try {
            cursor = sqliteHelper.find(sql, null);
            if (cursor == null)
                return null;

            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {
                obj = cursor.getString(0);
                cursor.moveToNext();
            }

            return obj;
        } catch (Exception ex) {
            return null;
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }

    /**
     * 查询
     *
     * @param tableName     表名称
     * @param columns       查询的列名称
     * @param selection     where子句的条件
     * @param selectionArgs
     * @return
     */
    public Cursor query(String tableName, String[] columns, String selection, String[] selectionArgs) {
        Cursor cur = null;
        try {
            cur = sqliteHelper.find(tableName, columns, selection, selectionArgs);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return cur;

    }

    /**
     * 将对象转换为ContentValues
     *
     * @param entity
     * @return
     */
    public ContentValues getContentValues(Object entity, String[] ref) {
        ContentValues values = new ContentValues();
        Field field1 = null;
        Class<?> entity_class = entity.getClass();
        try {
            for (int i = 0; i < ref.length; i++) {
                if (ref[i].length() <= 0) {
                    continue;
                }
                field1 = entity_class.getDeclaredField(ref[i]);
                String columname = field1.getName();
                Class<?> type = field1.getType();
                if (type == String.class) {
                    values.put(columname, (String) field1.get(entity));
                } else if (type == int.class || type == Integer.class) {
                    values.put(columname, field1.getInt(entity));
                } else if (type == float.class || type == Float.class) {
                    values.put(columname, field1.getFloat(entity));
                } else if (type == long.class || type == Long.class) {
                    values.put(columname, field1.getLong(entity));
                } else if (type == char.class) {
                    values.put(columname, (String) field1.get(entity));
                } else {
                    values.put(columname, (String) field1.get(entity));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return values;
    }

}
